<template>
  <div class="el-mr-materialWarehousing" v-loading="fullscreenLoading"
  element-loading-text="调用ERP接口中，请勿操作！"
    element-loading-background="rgba(0, 0, 0, 0.8)">
    <TableTitle>
      <slot>
        <p>
          流程进度
        </p>
      </slot>
    </TableTitle>
    <div>
      <li>
        <el-button type="success" icon="el-icon-refresh" @click="refresh" size="mini">刷新</el-button>
      </li>
      
    </div>
    <div >
      <el-steps :active="active" finish-status="success" style="margin-top: 10px;" align-center>
        <el-step title="缓存箱扫码" ></el-step>
        <el-step title="物料确认" ></el-step>
        <el-step title="物料入库" ></el-step>
        <el-step title="缓存箱回库" ></el-step>
      </el-steps>
    </div>
    <TableTitle>
      <slot>
        <p>
          扫码操作
        </p>
      </slot>
    </TableTitle>
    <TopSearch ref="topSearch">
      <slot>
       <!--
       <li>
          <el-button size="mini" type="primary" @click="handleHcxOut">缓存箱出库</el-button>
        </li>
        <li>
          <el-button size="mini" type="primary" @click="hcxScan">缓存箱扫码</el-button>
        </li>
        <li>
          <el-button size="mini" type="info" @click="handleMaterialHouse">物料入库</el-button>
        </li>
        <li>
          <el-button size="mini" type="info" @click="handleHcxBack">缓存箱回库</el-button>
        </li>
        -->
        <li>
          <el-button  size="mini" @click="backDeliveryClear">回退交接单</el-button>
        </li>
        <li>
          <el-button  size="mini" @click="lookupHcx">查看缓存箱</el-button>
        </li>
        <li>
          <el-button  size="mini" @click="repairMaterial">物料漏扫</el-button>
        </li>
        <li>
          <el-button  size="mini" @click="taskGoOn">继续执行</el-button>
        </li>
        <li class="showBoxTm">
          <p>缓存箱编码：<span v-if="boxTmShow">{{showBoxTm}}</span></p>
        </li>
        <el-drawer
          title="缓存箱列表"
          size="75%"
          :visible.sync="drawer.drawer"
          :with-header="false">
          <el-table :data="drawer.tableData" style="width: 100%" row-key="id" height=500  highlight-current-row :tree-props="{children: 'children', hasChildren: 'hasChildren'}" @current-change="currentTableData">
            <el-table-column  prop="workbinCode" label="缓存箱名字" width="150"> </el-table-column>
            <el-table-column prop="workbinStatus" label="状态" width="130"> </el-table-column>
            <el-table-column prop="roadway" label="巷道" width="120"> </el-table-column>
            <el-table-column prop="taskCnt" label="当前巷道排队任务数" width="120"> </el-table-column>
            <el-table-column prop="waitMin" label="预计等待时长(分钟)" width="120"> </el-table-column>
            <el-table-column prop="itemCode" label="图号"></el-table-column>
            <el-table-column prop="itemQty" label="入箱数量"></el-table-column>
            <el-table-column prop="qualityCode" label="质量编号/件号"></el-table-column>
            <el-table-column prop="mProductNumber" label="型号"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="150" ></el-table-column>
            <el-table-column prop="orderTime" label="下发时间" width="150" ></el-table-column>
            <el-table-column prop="parentTaskId" label="移库中" width="150" ></el-table-column>
            <!-- <el-table-column  fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="drawerHcxBack">回库</el-button>
              </template>
            </el-table-column> -->
          </el-table>
        </el-drawer>
        
      </slot>
    </TopSearch>
    <div style="overflow:hidden;">
      <div style="float:left;width:65%">
        <TableTitle>
          <slot>
            <p>
              待入库物料列表
            </p>
          </slot>
        </TableTitle>
        <Table @wareHousing="wareHousing"></Table>
      </div>
      <div style="float:right;width:34%">
        <TableTitle>
          <slot>
            <p>
              已入库物料列表
            </p>
          </slot>
        </TableTitle>
        <AlTable></AlTable>
      </div>
    </div>
    <Boxinfo></Boxinfo>
  </div>
</template>
<script>
import TopSearch from "../../../../components/TopSearch.vue";
import Table from "./components/MathouseTable.vue";
import AlTable from "./components/MathouseAlTable.vue";
import Boxinfo from "./components/MathouseBoxInfo.vue"
import TableTitle from "../../../../components/TableTitle.vue";
import request from'@/utils/request.js'
import { materialReceipt,searchWorkbinMaterial,bufferBoxOut,bufferBoxWarehousing } from "@/utils/api.js"
export default {
  name: "MaterialWarehousing",
  inject:['reload'],
  components: {
    TopSearch,
    Table,
    AlTable,
    Boxinfo,
    TableTitle
  },
  data(){
    return {
      // 缓存箱编码
      boxTm:'',
      indexTm:'',
      showBoxTm:'',
      // 表单样式
      formLabelWidth:'50px',
      // 勾选的ID
      infoid:'',
      // 缓存箱编码是否展示
      boxTmShow:false,
      // 接收上表所勾选的物料信息的条码
      checkMaterialBarcode:[],
      checkMaterialList:[],
      // 大件入库参数
      bigInfoData:[],
      // 存储信息框修改后的数据
      mwBoxLists:[],
      hcxBoxBack:'',
      hcxBoxBackNum:0,
      hcxBoxIn:'',
      marterialResult:[],
      // 步骤条
      active: 0,
      // 9005扫码两次参数
      jnnw:0,
      // 9002扫码两次参数
      jnne:0,
      marterialNumber:0,
      // 是否进行了物料确认
      isCheckMarterial:false,
      // 是否进行了缓存箱扫码
      hcxScanNum:false,
      // 物料入库成功参数
      marterialInRoom:false,
      fullscreenLoading:false,
      //yebo 回退交接单集合
      backDeliverys:[],
      drawer:{
        drawer:false,
        tableData:[],
        currentData:{}
      }
      
    }
  },
  methods:{
    next() {
        if (this.active++ > 2){
          setTimeout(()=>{
            this.active = 0
          },1000)
        }
        //console.log(this.active)
      },
    // 统一扫码判断接口方法
    scanning(){
      console.log(this.indexTm);
      if(this.indexTm.length == 12&&(this.indexTm.indexOf("11208003")==0||this.indexTm.indexOf("31208003")==0)){
        // 限制缓存箱扫码只能扫一次
        if(this.hcxScanNum){
          // 缓存箱已经扫码
          this.$Alert({
            title: "失败",
            message: '请勿重复扫缓存箱编码',
            type: "error",
          })
        }else{
          // 缓存箱扫码
          this.$options.methods.hcxScan.bind(this)()
          
        }
      }else if(this.indexTm == 9005){
        
        if(this.jnnw == 1){
          if(this.isCheckMarterial){
            this.fullscreenLoading = true
            // 物料入库
            this.$options.methods.handleMaterialHouse.bind(this)();
            var loadingTime = setInterval(() => {
              clearInterval(loadingTime);
              this.fullscreenLoading = false;
              this.isCheckMarterial = false;
              //yebo 2023-07-25 清空物料信息，防止因为界面没返回用户重复操作
              this.$bus.$emit('mrMwClearMaterialList','清空已确认物料的条码');
            }, 5000);
            

            this.jnnw++;
          }else{
            this.jnnw = 0
            this.$Alert({
              title: "失败",
              message: '物料未全部确认！',
              type: "error",
            })
          }
          
        }else if(this.jnnw>1){
          this.$Alert({title: "失败",message: '已经扫码9005了，请不要重复扫码',type: "error"});
        }else{
          this.jnnw++
        }
        console.log(this.jnnw)
      }else if(this.indexTm == 9002){
        if(this.jnnw > 1){
          this.jnne++
          if(this.jnne == 2){
            // 缓存箱回库
            this.$options.methods.handleHcxBack.bind(this)()
          }
        }else{
          this.$Alert({
            title: "失败",
            message: '请先物料入库执行保存',
            type: "error",
          })
        }
        
      }else if(this.indexTm.includes('"CPHGZ"')){//扫码条码是否成品
        let indexTmFin = this.indexTm
        for(let mn=0;mn<this.marterialResult.length;mn++){
          if(JSON.parse(indexTmFin).CPHGZ == this.marterialResult[mn].mesCheckQualiticationId){
            this.$bus.$emit('mrMwMaterialListSend',{msg:this.marterialResult[mn].mesCheckQualiticationId,index:mn});
            this.marterialNumber++;
            this.$bus.$emit('countNum',this.marterialNumber)
            this.$bus.$emit('countTotalNum',this.marterialResult.length)
          }
        }
 
        if(this.marterialNumber == this.marterialResult.length){
          // 进度条
          this.$options.methods.next.bind(this)()
          this.isCheckMarterial = true
          this.marterialNumber = 0
        }
      }else if(this.indexTm.includes('"CKCODE"')){//扫码是标准件
        let indexTmFin = this.indexTm
        for(let mn=0;mn<this.marterialResult.length;mn++){
          if(JSON.parse(indexTmFin).CKCODE == this.marterialResult[mn].barcode || JSON.parse(indexTmFin).CKCODE == this.marterialResult[mn].ckBarCode){
            this.$bus.$emit('mrMwMaterialListSend',{msg:this.marterialResult[mn].barcode,index:mn});
            this.marterialNumber++;
            this.$bus.$emit('countNum',this.marterialNumber)
            this.$bus.$emit('countTotalNum',this.marterialResult.length)
          }
        }
 
        if(this.marterialNumber == this.marterialResult.length){
          // 进度条
          this.$options.methods.next.bind(this)()
          this.isCheckMarterial = true
          this.marterialNumber = 0
        }
      }else {
        // this.$bus.$emit('mrMwMaterialListSend',this.indexTm)
        for(let mn=0;mn<this.marterialResult.length;mn++){
          if(this.indexTm == this.marterialResult[mn].barcode){
            this.$bus.$emit('mrMwMaterialListSend',{msg:this.marterialResult[mn].barcode,index:mn})
            this.marterialNumber++;
            this.$bus.$emit('countNum',this.marterialNumber)
            this.$bus.$emit('countTotalNum',this.marterialResult.length)
          }
        }
        if(this.marterialNumber == this.marterialResult.length){
          // 进度条
          this.$options.methods.next.bind(this)()
          this.isCheckMarterial = true
          this.marterialNumber = 0
        }
      }
    },
    // 缓存箱出库
    handleHcxOut(){
      let hcxBoxInfoList = []
      for(let i=0;i<this.hcxBoxIn.length;i++){
        hcxBoxInfoList.push(this.hcxBoxIn[i].itemCode)
      }
      // console.log(this.hcxBoxIn[0].itemCode,hcxBoxInfoList)
      bufferBoxOut({
        itemCodes:hcxBoxInfoList
      }).then((res)=>{
        if(res.data.retCode == 200){
          // 进度条
          this.$options.methods.next.bind(this)()
          console.log('缓存箱出库按钮',res)
          this.$Alert({
            title: "成功",
            message: res.data.message,
            type: "success",
          })
        }else {
          console.log('缓存箱出库按钮',res)
          this.$Alert({
            title: "失败",
            message: res.data.message,
            type: "error",
          })
        }
      })
    },
    // 缓存箱条码扫码
    hcxScan(){
      // 显示缓存箱条码
      this.showBoxTm = this.indexTm
      // 获取下方缓存箱 将其显示
      let boxInfo = document.querySelector('.mr-mathouseBoxinfo')
      if(this.showBoxTm == ''){
        // alert('扫码未识别到')
        this.$Alert({
            title: "错误",
            message: '条码不能为空！',
            type: "error",
          })
      }else {
        // console.log(1111,this.showBoxTm)
        // 缓存箱扫码按钮接口
        searchWorkbinMaterial({
          workbinCode:this.showBoxTm
        }).then((res)=>{
          if(res.data.retCode == 200){
            // 解除物料框隐藏
            boxInfo.style.display = 'inline'
            // 解除缓存箱条码隐藏
            this.boxTmShow = true
            // console.log(this.showBoxTm)
            // 将物料箱信息传给BoxInfo组件
            this.$bus.$emit('mwHcBoxInfo',res.data.responseBody)
            // 如果是3开头的hcx 就是大件传参显示下拉框
            var hcxtmArr = this.showBoxTm.split('')
            if(hcxtmArr[0] == 3){
              this.$bus.$emit('mwBighcxtm','大件')
            }
            console.log("res",res.data.responseBody);
            // 将物料箱信息传给待入库物料Table组件--高亮
            this.$bus.$emit('mwHcxmGaoLiang',res.data.responseBody)
            // 保存缓存箱扫码拿到的物料信息列表
            this.marterialResult = res.data.responseBody
            //统计扫码总数
            this.$bus.$emit('countTotalNum',this.marterialResult.length)
            // 清空input 聚焦
            this.$refs.topSearch.makeTmNull()
            this.$refs.topSearch.openScan()
            // 进度条
            this.$options.methods.next.bind(this)()
            // 改变缓存箱扫码确认参数
            this.hcxScanNum = true
          }else {
            this.$Alert({
              title: "错误",
              message: res.data.message,
              type: "error",
            })
          }
          console.log('缓存箱扫码',res)
          // this.showBoxTm = res.data.responseBody[0].workbinCode
          
        })
        
      }
    },
    // 接收Table传来的info
    wareHousing(value){
      this.infoid = value[0].wmsDeliveryPlanId
      console.log('接收成功1',this.infoid)
    },
    // 物料入库按钮
    handleMaterialHouse(){
      sessionStorage.getItem("userUnitsNumber")
      let loginIngo = sessionStorage.getItem("userName") + sessionStorage.getItem("userJobNumber")
      let loginBm = sessionStorage.getItem("userUnits");

      materialReceipt({
        account:loginIngo,
        departid:loginBm,
        planDTOs:this.mwBoxLists,
        workbinCode:this.showBoxTm,
        // 已确认物料的条码集合
        barcodes:this.checkMaterialBarcode,
      }).then((res)=>{
        if(res.data.retCode == 200){
          this.fullscreenLoading = false
          // 确认物料成功参数
          this.marterialInRoom = true
          
          // 进度条
          this.$options.methods.next.bind(this)()
          console.log('物料入库按钮',res)
          this.$Alert({title: "成功", message: res.data.message,type: "success"})
          // 清空input 聚焦
            this.$refs.topSearch.makeTmNull()
            this.$refs.topSearch.openScan()
          // 清空已确认物料的条码
          this.$bus.$emit('mrMwClearMaterialList','清空已确认物料的条码')
          //清空计数器
          this.$bus.$emit('countNum',0)
          this.$bus.$emit('countTotalNum',0)
          // this.$bus.$emit('mrMwhClearHcxInfo','清空')
          this.$bus.$emit("mrMwReTable",null);//刷新表格
        }else {
          this.fullscreenLoading = false
          console.log('物料入库按钮',res)
          this.$Alert({
            title: "失败",
            message: res.data.message,
            type: "error",
          })
        }
      })
      
    },
    // 缓存箱回库
    handleHcxBack(){
      bufferBoxWarehousing({
          workbinCode:this.showBoxTm
        }).then((res)=>{
          console.log('缓存箱回库',res)
          if(res.data.retCode == 200){
            // // 缓存箱回库后将上一个缓存箱物料清空 --- 该操作好像在物料入库的时候就做了
            // this.$bus.$emit('mrMwhClearHcxInfo','清空')
            let boxInfo = document.querySelector('.mr-mathouseBoxinfo')
            boxInfo.style.display = 'none'
            this.boxTmShow = false
            this.$Alert({
              title: "成功",
              message: res.data.message,
              type: "success",
            });
            // 清空条码框
            this.$refs.topSearch.makeTmNull()
            // 聚焦条码框
            this.$refs.topSearch.openScan()
            // 刷新Table
              this.$bus.$emit('mrMwReTable','刷新')
              this.hcxBoxBackNum = 0
            // 进度条
            this.$options.methods.next.bind(this)()
            // 清空两次操作码参数
            this.jnne = 0
            this.jnnw = 0
            // 完整操作完成后改变缓存箱扫码确认参数
            this.hcxScanNum = false
          }else {
            this.$Alert({
              title: "失败",
              message: res.data.message,
              type: "error",
            });
          }
        })
    },
    //漏扫物料
    repairMaterial(){
      console.log(this.showBoxTm);
      request.post("/materialReceipt/updateRepair",{workbinCode:this.showBoxTm}).then((res)=>{
        this.reload();
        if(res.data.retCode=="200"){
          
          this.$Alert({title: "成功",message: res.data.message,type: "success"});
          
        }else{
          this.$Alert({title: "无漏扫物料",message: res.data.message,type: "error"});
        }
      })
    } ,
    //交接单状态重复
    backDeliveryClear(){
      //backDeliverys
      if(this.backDeliverys.length==0){
        this.$Alert({title: "错误",message: '请至少选择一条数据！',type: "error"});
        return ;
      }
      var confirm = window.confirm("是否确认回退数据?");
      if(!confirm){
        return;
      }
      request.post("/materialReceipt/backDeliverys",this.backDeliverys).then((res)=>{
        if(res.data.retCode=="200"){
          this.$Alert({title: "成功",message: res.data.message,type: "success"});
          this.$bus.$emit("mrMwReTable",null);//刷新表格
        }else{
          this.$Alert({title: "错误",message: res.data.message,type: "error"});
        }
      })
    },
    currentTableData(val){
      console.log("val",val);
      this.drawer.currentData = val;
    },
    lookupHcx(){
      this.drawer.drawer = true;
      this.drawer.tableData = [];
      var that = this;
      request.post("/materialReceipt/queryReceiveGkLog",{}).then((res)=>{
        console.log("res1",res);
        that.drawer.tableData = res.data;
      })
    },
    taskGoOn(){
      request.post("/taskGoOn/receiveGoingOn",{}).then((res)=>{
        console.log("res1",res);
        this.$Alert({ title: "成功",message: res.data.message,type: "success"});
      })
    },
    drawerHcxBack(){
      var that = this;
      if(this.drawer.currentData==={}){
        return ;
      }
     
      bufferBoxWarehousing({
          workbinCode:this.drawer.currentData.workbinCode
        }).then((res)=>{
          if(res.data.retCode == 200){
            // // 缓存箱回库后将上一个缓存箱物料清空 --- 该操作好像在物料入库的时候就做了
            // this.$bus.$emit('mrMwhClearHcxInfo','清空')
            let boxInfo = document.querySelector('.mr-mathouseBoxinfo')
            boxInfo.style.display = 'none';
            that.boxTmShow = false;
            this.$Alert({
              title: "成功",
              message: res.data.message,
              type: "success",
            });
            // 清空条码框
            that.$refs.topSearch.makeTmNull()
            // 聚焦条码框
            that.$refs.topSearch.openScan()
            // 刷新Table
            that.$bus.$emit('mrMwReTable','刷新')
            that.hcxBoxBackNum = 0
            // 进度条
            that.$options.methods.next.bind(this)()
            // 清空两次操作码参数
            that.jnne = 0
            that.jnnw = 0
            // 完整操作完成后改变缓存箱扫码确认参数
            that.hcxScanNum = false
          }else {
            this.$Alert({
              title: "失败",
              message: res.data.message,
              type: "error",
            });
          }
        })
    },
    refresh() {
    console.log("刷新");
		this.reload();
    },
  },
  
  mounted(){
    // 接收大件组装data参数
    this.$bus.$on('wmsBigInfoList',(e)=>{
      this.bigInfoData = e
    })
    // 接收上表所勾选的物料信息的条码
    this.$bus.$on('mwCheckMaterialBarcode',(e)=>{
      this.checkMaterialBarcode = e
    });

    // 接收扫码的缓存箱条码this.$bus.$emit('saoma',this.inTiaoma)
    this.$bus.$on('saoma',(e)=>{
      this.indexTm = e
      // console.log(this.boxTm)
    })
    // 将修改的数据返给首页
    this.$bus.$on('mwBoxList',(e)=>{
      this.mwBoxLists = e
      // 清空条码框
      this.$refs.topSearch.makeTmNull()
      // 聚焦条码框
      this.$refs.topSearch.openScan()
    })
    // 接收Table传来的出库 回库 数据信息
    this.$bus.$on('mwMbBoxInfo',(e)=>{
      this.hcxBoxBack = e
      this.hcxBoxIn = e
      // console.log(this.hcxBoxIn)
    })
    //一键确认设置校验通过
    this.$bus.$on("oneClickConfirm",()=>{
      this.isCheckMarterial = true;
    });
    //yebo 新增，获取要回退的交接单数据
    this.$bus.$on("selectBackDeliverys",(data)=>{
        this.backDeliverys = data;
    })
  }
};
</script>
<style scoped>
.el-button--info {
  background: #29bacd;
  border-color: #29bacd;
}
.el-button--info:hover {
  background: #137683;
  border-color: #137683;
}
.showBoxTm span{
  font-size: 20px !important;
  
}
</style>